package com.kcnet.qk.activity;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.kcnet.qk.Common.FuncItemFactory;
import com.kcnet.qk.MyApplication;
import com.kcnet.qk.R;
import com.kcnet.qk.adapter.FuncAdapter;
import com.kcnet.qk.constant.Const;
import com.kcnet.qk.controller.MyWindowManager;
import com.kcnet.qk.netty.NettyClient;
import com.kcnet.qk.service.CoreService;
import com.kcnet.qk.service.UpdateService;
import com.kcnet.qk.util.AppUtil;
import com.kcnet.qk.util.PreferenceHelper;
import com.kcnet.qk.util.ToastUtil;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import butterknife.BindView;

/**
 * app main entry
 */
public class MainActivity extends BaseActivity {

    private final static int MINI_VERSION_CODE = 16;
    private final static String SNACKBAR_TXT = "当前您使用的系统版本过低，请更新高版本系统再使用";

    @BindView(R.id.ll)
    FrameLayout mLlRootView;

    @BindView(R.id.bannerContainer)
    FrameLayout mFlBannerContainer;

    @BindView(R.id.ryv)
    RecyclerView mRecyclerView;

    private boolean mIsFirstJump = false;
    private FuncAdapter mAdapter;

    private android.app.Dialog Dialog;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new FuncAdapter(this, FuncItemFactory.getInstance().createmMainFuncItems());
        mRecyclerView.setAdapter(mAdapter);
        startService(new Intent(this,CoreService.class));
        //AppUtil.jumpToWx(this);
        if (!AppUtil.checkPermission(this)) {
            AppUtil.jumpSetting(this);
        }

    }

    @Override
    protected void initData() {
        // only for build version larger equal than api 18

    }

    @Override
    protected void setListener() {
        mAdapter.setOnItemClickListener(new FuncAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String funcName = FuncItemFactory.getInstance().createmMainFuncItems().get(position).funcName;
                switch (funcName) {

                    case FuncItemFactory.TAB_ADD_FIREND_MOD:
//                        Intent intent =new Intent(MainActivity.this,AddFirendActivity.class);
//                        startActivity(intent);
                        break;
                    case FuncItemFactory.TAB_HDYH:
                     Intent intent2 =new Intent(MainActivity.this,GroupActivity.class);
                      startActivity(intent2);
                        break;

                    case FuncItemFactory.STOP_ADD_PEOPLE:
                        PreferenceHelper.putBoolean(Const.PREF_KEY_STOP_AUTO_FLAG, false);
                        EventBus.getDefault().post(new Boolean(false));
                        toast("设置成功");
                        break;
                    case FuncItemFactory.FLOW_WINDOW:
                        showFlowWindow();
                        break;
                    case FuncItemFactory.SOCKET_CON_SERVER:
                        showInputIP();
                        break;
                    case FuncItemFactory.SOCKET_CON_SERVER_STATUS:
                        ToastUtil.showToast(getBaseContext(), "连接状态:" + NettyClient.getInstance().getConnectStatus());
                        break;

                    case FuncItemFactory.APP_CHECK_UPDATE:
                        checkUpdataApp();
                        break;
                }
            }
        });
    }


    /**
     * 检测更新APP升级
     */
    private void checkUpdataApp() {
        Log.d("HTML","checkUpdataApp:");
        AjaxParams ps = new AjaxParams();
        final  int version = AppUtil.getVersionCode(this);
        ps.put("version",""+AppUtil.getVersionCode(this));
        MyApplication.http.get("http://control.likangjun.com/api/index/appVersion", ps, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                super.onSuccess(s);
                Log.d("HTML","onSuccess:"+s);
                try {
                    JSONObject jb = new JSONObject(s);
                    if(jb.getInt("code") == 1){
                        int jbversion =  jb.getJSONObject("data").getInt("version");
                        String url =  jb.getJSONObject("data").getString("url");
                        if(jbversion > version){
                            Intent intent  = new Intent(MainActivity.this,UpdateService.class);
                            intent.putExtra("appname","FB精灵");
                            intent.putExtra("appurl",url);
                            startService(intent);
                        }
                    }else {

                        ToastUtil.showToast(MainActivity.this,jb.getString("msg"));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Log.d("HTML","onFailure:"+strMsg);
                ToastUtil.showToast(MainActivity.this,R.string.req_error);
            }
        });
    }



    public void showInputIP() {
        // AlertDialog dialog = alertDialog.create();
        if (Dialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setTitle("请输入IP");
            final EditText editText = new EditText(this);
            editText.setHint("请输入IP地址");
            editText.setText(PreferenceHelper.getString(Const.HOST, ""));
            builder.setView(editText);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    String ip = editText.getText().toString();
                    if (TextUtils.isEmpty(ip)) {
                        Toast.makeText(getBaseContext(), "不允许输入为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    PreferenceHelper.putString(Const.HOST, ip);
                    dialog.dismiss();
                    connect();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            Dialog = builder.create();
            Dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }
        if (!Dialog.isShowing()) {
            Dialog.show();
        }
    }



    private void jumpSetting() {
        // jump to setting permission
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        startActivity(intent);
    }


    @Override
    protected void onResume() {
        if (mIsFirstJump && AppUtil.checkPermission(this)) {
            AppUtil.jumpToFb(this);
            mIsFirstJump = false;
        }
        super.onResume();
    }

    private void showFlowWindow() {
        if (!MyWindowManager.isWindowShowing()) {
            MyWindowManager.createSmallWindow(getApplicationContext());
        } else {
            toast("已显示悬浮窗了");
        }
    }
    private void connect() {
        Intent intent = new Intent(this,CoreService.class);
        intent.putExtra("id",1);
        startService(intent);
    }



}

